<template>
  <div class="get_code">
    <span @click="getCode">
      {{ msg }}
    </span>
  </div>
</template>
<script>
import _ from 'lodash'
import { validTel } from '@/utils/validate'
export default {
  props: {
    phone: {
      type: String
    }
  },
  data() {
    return {
      fsPhone: '',
      msg: '免费获取验证码',
      count: 60
    }
  },
  methods: {
    // 函数节流 防止重复点击
    getCode: _.throttle(async function() {
      let interval = {}
      if (this.msg === '免费获取验证码') {
        if (!validTel(this.phone)) {
          this.$message({ message: '手机号格式错误', type: 'error' })
          return false
        }
        // const res = await getCode({
        //   phone: '+86' + this.phone,
        //   templateId: '5ca98f730645455aab2c03d2f54cce0e',
        //   sender: '8820061613750'
        // })
        // if (res.code === 'success') {
        //   this.$emit('getCode', res.data.fsPhone)
        // }
        this.msg = this.count + '秒后重新发送'
        this.count--
        interval = setInterval(() => {
          if (this.count === 0) {
            clearInterval(interval)
            this.msg = '免费获取验证码'
            this.count = 60
            return true
          } else {
            this.msg = this.count + '秒后重新发送'
            this.count--
            return false
          }
        }, 1000)
      }
    }, 1000)
  }
}
</script>
<style scoped>
</style>
